21. 无状态组件

无状态组件

将UI组件改成一个无状态组件,无状态组件的性能比较高,原因是无状态组件返回的就是一个js对象。

原来的UI组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { Component } from 'react'
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd';

class TodoListUI extends Component {
render(){
return (
<div>
<Input value={ this.props.inputVlaue } onChange = { this.props.handleChange } placeholder="在此输入文本..." style={{ width:'300px', marginRight:'10px' }}/>
<Button type="primary" onClick={ this.props.handleBtnClick }>提交</Button>
<List
style={{ width:'300px', marginTop:'10px' }}
bordered
dataSource={ this.props.list }
renderItem={(item, index) => (<List.Item onClick= { (index) => this.props.handleBtnDelete(index) }>{item}</List.Item>)}
/>
</div>
)
}
}

export default TodoListUI;

无状态组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { Component } from 'react'
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd';

// 不使用js对象的方式,而是定一个变量,内容为一个函数,函数返回jsx
const TodoListUI = (props) => {
return (
<div>
<Input value={ props.inputVlaue } onChange = { props.handleChange } placeholder="在此输入文本..." style={{ width:'300px', marginRight:'10px' }}/>
<Button type="primary" onClick={ props.handleBtnClick }>提交</Button>
<List
style={{ width:'300px', marginTop:'10px' }}
bordered
dataSource={ props.list }
renderItem={(item, index) => (<List.Item onClick= { (index) => props.handleBtnDelete(index) }>{item}</List.Item>)}
/>
</div>
)
}

export default TodoListUI;

https://github.com/rexyan/simple_react/tree/%E6%97%A0%E7%8A%B6%E6%80%81%E7%BB%84%E4%BB%B6